/**
 * @Description:
 * @author 紫霞
 * @since 2019/1/17
 */
// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import { Form, Col, Row, Button, Input, Select, DatePicker, Radio, Cascader, Checkbox, Tag, Upload, Icon, Modal, message, Tooltip } from 'antd'
import locale from 'antd/lib/date-picker/locale/zh_CN';
import moment from 'moment';
import 'moment/locale/zh-cn';
import { CollapsiblePanels } from 'widget/CollapsiblePanels/index'
moment.locale('zh-cn');
const confirm = Modal.confirm;
const { TextArea } = Input;
const { RangePicker } = DatePicker;
const RadioGroup = Radio.Group;
const FormItem = Form.Item
const Option = Select.Option;
//引用listPage
import ListPage from 'widget/PageTmpl/ListPage'

//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'
import Uploader from 'widget/Upload'
// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
// 当前组件样式
import styles from './infoDetailStyle.less'
import classnames from 'classnames/bind'
let cx = classnames.bind(styles);
//引入富文本编辑器
import Editor from '../../../../widget/Editor/Editor'
import { calculate_object_name, uploadObject2OSS } from '../../../../utils/upload'
// import KingEditor from '../../../../widget/Editor/KingEditor.js'

import Ueditor from '../../../../widget/Editor/Ueditor.js'
import ImgCutting from 'widget/ImgCutting/ImgCuttingView';
import info_cover_01 from '../../../../assets/img/infoAndActivity/info_cover_01.png'
import info_cover_02 from '../../../../assets/img/infoAndActivity/info_cover_02.png'
import infoDetail_demo from '../../../../assets/img/infoAndActivity/infoDetail_demo.png'
/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */
const formItemLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
}
const formItemLayout2 = {
  labelCol: { span: 12 },
  wrapperCol: { span: 12 },
}

const routeView = function ({ dispatch, model, form }) {
  // 表单的子函数
  const { resetFields, getFieldDecorator, validateFields, setFieldsValue } = form
  // 取出model对象，命名空间
  const { modelObj, namespace } = model

  // modelObj.xxx获取model中状态机的值
  let { showEditor, editValue, disabledLink, detail, visible, tagALL, areaList, actionType, contentId,
    estateList, showTime, imgModal, isSubmit } = modelObj

  console.log('detail', detail)
  // 处理确定事件
  function handleOk(imgUrl) {
    console.log('裁剪后上传的图片地址为：', imgUrl);
    toggleDialog(false);
  }

  // 处理关闭事件
  function handleClose(e) {
    toggleDialog(false);
  }

  // 打开/关闭裁剪对话框
  function toggleDialog(visible) {
    dispatch({
      type: `${namespace}/updateModel`,
      payload: { visible }
    });
  }
  function changeCity(value) {
    detail.province = value[0]
    detail.city = value[1]
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { detail }
    });
    dispatch({
      type: `${namespace}/getBusinessList`,
      payload: { province: value[0], city: value[1] }
    })
  }

  //所有类型改变时（除date image）
  function inputChange(val, type) {
    console.log(val)
    detail[type] = val
    dispatch({
      type: `${namespace}/updateModel`,
      payload: { detail }
    });
    if (detail.channel && detail.channel == 2 || detail.channel == 3) {
      dispatch({
        type: `${namespace}/updateModel`,
        payload: { showTime: false }
      });
    } else {
      dispatch({
        type: `${namespace}/updateModel`,
        payload: { showTime: true }
      });
    }
  }
  //图片删除时
  function removeImgUrl(index, item) {
    detail.titleImgUrl = ''
    dispatch({
      type: `${namespace}/updateModel`,
      payload: { detail }
    });
  }
  //图片增加时
  function updateImageModel(value) {
    detail.titleImgUrl = value
    dispatch({
      type: `${namespace}/updateModel`,
      payload: { detail }
    });
  };
  //date改变时
  function dateChange(date, dateString) {
    detail['startDate'] = dateString[0]
    detail['endDate'] = dateString[1]
    dispatch({
      type: `${namespace}/updateModel`,
      payload: { detail }
    });
  }

  // 获取项目选项
  function getPorjectOption() {
    if (estateList) {
      return estateList.map((item, idx) =>
        <Select.Option key={idx} value={item.productId}>{item.name}</Select.Option>
      )
    } else {
      return null
    }
  }

  function getTypeList() {
    let list = [
      {"label": "商品房", "value": '1'},
      {"label": "保障房", "value": '2'},
      {"label": "改造", "value": '3'},
      {"label": "土地出让公告", "value": '10'},
      {"label": "土地划拨供地公示", "value": '11'},
      {"label": "土地成交信息", "value": '12'},
    ]
    return list.map((item, idx) =>
        <Select.Option key={idx} value={item.value}>{item.label}</Select.Option>
      )
  }


  //编辑
  function edit() {
    dispatch({
      type: `${namespace}/updateModel`,
      payload: { actionType: 'edit' }
    });
  }

  //删除
  function deleteContent() {
    confirm({
      title: '删除确认',
      content: '您真的要删除此条资讯吗?',
      okText: '确认',
      okType: 'primary',
      cancelText: '取消',
      onOk() {
        dispatch({
          type: `${namespace}/deleteContent`
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }
  function toDetail() {
    hashHistory.push({
      pathname: MODULE_TO_ROUTES[namespace].urlArray[0],
      query: { type: 'edit', }
    });
  }
  //提交
  function submit() {
    // console.log(detail)
    form.validateFields((err, values) => {
      console.log(err)
      if (!err) {
        dispatch({
          type: `${namespace}/sumbit`
        })
      }
    });
  }
  const changeState = (payload) => {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { ...payload }
    })
  }

  function changeImgModal(visible = false, srcs = []) {
    imgModal.visible = visible
    imgModal.srcs = srcs || modelObj.srcs
    changeState({ imgModal })
  }
  return (
    <div className={cx('pageLayout')}>
      <div className='public_listMain'>
        <div className={"functionButton"}>
          {actionType == "add" || actionType == "edit" ?
            <Button type='primary' disabled={modelObj.btndisabled} onClick={e => submit()} loading={modelObj.btnLoading}>提交</Button> : null}
          {actionType == 'detail' ?
            <Button type='primary' onClick={e => deleteContent()} loading={modelObj.btnLoading}>删除</Button> : null}
          {actionType == 'detail' ?
            <Button type='primary' onClick={e => edit(contentId)}>编辑</Button> : null}
        </div>
        <Form>
          <div className="boxShadow">
            <CollapsiblePanels title={'封面图'} hideUpDownBtn={true} >
              <Row>
                <Col span={6}>
                  <FormItem
                    {...formItemLayout}
                    required='true'
                    extra={actionType == 'detail' ? '' : '图片分辨率需为512px*336px，且文件大小在500kb以下，支持jpg，png格式。'}
                    label="封面图">
                    <Uploader uploadedUrls={detail.titleImgUrl}
                      removeFileCbf={() => { removeImgUrl() }}
                      uploadSuccessCbf={(imgUrl) => { updateImageModel(imgUrl) }}
                      showType={'3'}
                      minCropBoxWidth={512}
                      minCropBoxHeight={336}
                      fileType='image'
                      fileMaxSize='0.5'
                      maxFiles='1' />
                  </FormItem>
                </Col>
                {/* <Col span={6}>
                  <div>
                    <Icon type="question-circle" className={'mgr1'} style={{ color: '#08c' }} />
                    <a href="javascript:void(0)" onClick={() => { changeImgModal(true, [info_cover_01, info_cover_02]) }}>封面图显示在哪里?</a>
                  </div>
                </Col> */}
              </Row>
            </CollapsiblePanels>
            <CollapsiblePanels title={actionType == 'add' ? '编辑内容' : <div>政策内容
            {actionType && actionType == 'detail' ?
                <div className={cx('updateInfo')}><span>创建人：{detail.creator}</span> <span>创建时间：{detail.createTime}</span> <span className={cx(detail.updatePerson ? '' : 'hidden')}>更新人：{detail.updatePerson}</span> <span className={cx(detail.updateTime ? '' : 'hidden')}>更新时间： {detail.updateTime}</span></div>
                : null}
            </div>} hideUpDownBtn={false} >
              <Row>
                <Col className="col" span={6}>
                  <FormItem
                    {...formItemLayout}
                    label='省市'>
                    {getFieldDecorator('city', {
                      initialValue: (detail.productResDtoList && detail.productResDtoList.length > 0 ? [detail.productResDtoList[0].province, detail.productResDtoList[0].city] : '')
                    })(
                      <Cascader
                        options={areaList}
                        disabled={actionType == 'detail'}
                        onChange={changeCity}
                        placeholder={'请选择所属城市'}
                      // changeOnSelect
                      />
                    )}
                  </FormItem>
                </Col>
                
                <Col className="col" span={6}>
                  <FormItem
                    {...formItemLayout}
                    label='项目'>
                    {getFieldDecorator('businessId', {
                      initialValue: (detail.productResDtoList && detail.productResDtoList.length > 0?detail.productResDtoList[0].productName:''),
                      rules: [
                        { required: false, whitespace: true, message: '请先选择省市再选择项目' },
                      ],
                    })(
                      <Select
                        placeholder={"请选择项目"}
                        disabled={actionType == 'detail'}
                        onChange={(e) => inputChange(e, 'businessId')}>
                        {getPorjectOption()}
                      </Select>
                    )}
                  </FormItem>
                </Col>
                <Col className="col" span={6}>
                  <FormItem
                    {...formItemLayout}
                    label='分类'>
                    {getFieldDecorator('type', {
                      initialValue: detail.type? detail.type:"",
                      rules: [
                        { required: true, whitespace: true, message: '请选择分类' },
                      ],
                    })(
                      <Select
                        placeholder={"请选择分类"}
                        disabled={actionType == 'detail'}
                        onChange={(e) => inputChange(e, 'type')}>
                        {getTypeList()}
                      </Select>
                    )}
                  </FormItem>
                </Col>
                <Col span={5}>
                  <FormItem {...formItemLayout2} label="是否推送">
                    {getFieldDecorator('isPush', {
                      initialValue: detail.isPush,
                      rules: [
                        { required: false, whitespace: true, message: '请选择是否推送', type: 'boolean' },
                      ],
                    })(
                      <Radio.Group onChange={(e) => inputChange(e.target.value, 'isPush')} disabled={actionType == 'detail'}>
                        <Radio value={true}>是</Radio>
                        <Radio value={false}>否</Radio>
                      </Radio.Group>
                    )}
                  </FormItem>
                </Col>
                {detail.isPush &&
                  <Col className="col" span={6}>
                    <FormItem
                      {...formItemLayout}
                      label='推送对象'>
                      {getFieldDecorator('pushType', {
                        initialValue: detail.pushType ? detail.pushType + '' : '',
                        rules: [
                          { required: false, whitespace: true, message: '请选择类型' },
                        ],
                      })(<Select placeholder={"请选择类型"} onChange={(val) => inputChange(val, 'pushType')} disabled={actionType == 'detail'}>
                        <Option value="1">推送专业经纪人</Option>
                        <Option value="2">推送关注楼盘用户</Option>
                        <Option value="3">以上两者</Option>

                      </Select>)}
                    </FormItem>
                  </Col>
                }
                {/* <Col className="col" span={6}>
                <FormItem
                  {...formItemLayout}
                  label='推送对象'>
                  {getFieldDecorator('pushType', {
                    initialValue: detail.pushType?detail.pushType+'':'',
                    rules: [
                      { required: false, whitespace: true, message: '请选择类型' },
                    ],
                  })(<Select placeholder={"请选择类型"} onChange={(val) => inputChange(val, 'pushType')} disabled={actionType == 'detail' ||actionType =="edit"}>
                    <Option value="3">全部</Option>
                    <Option value="1">推送专业经纪人</Option>
                    <Option value="2">推送关注楼盘对象</Option>
                  </Select>)}
                </FormItem>
              </Col> */}

              </Row>
              <Row>
                <Col className="col" span={6}>
                  <FormItem
                    {...formItemLayout}
                    label='标题'>
                    {getFieldDecorator('title', {
                      initialValue: detail.title,
                      rules: [
                        { required: true, whitespace: true, message: '请输入标题' },
                        { max: 50, message: '最多只能输入50个字' },
                      ],
                    })(<Input
                      placeholder={'请输入标题'}
                      disabled={actionType == 'detail'}
                      onChange={(e) => { inputChange(e.target.value, 'title') }}
                    />)}
                  </FormItem>
                </Col>
                <Col className="col" span={6}>
                  <FormItem {...formItemLayout}
                    label="标签">
                    {getFieldDecorator('tags', {
                      initialValue: detail.tags ? detail.tags : [],
                      rules: [
                        { required: false, type: 'array', whitespace: true, message: '请输入资讯标签' },
                      ],
                    })(<Select
                      mode="multiple"
                      size='default'
                      showSearch
                      filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                      notFoundContent='没有此标签'
                      placeholder="请选择标签"
                      disabled={actionType == 'detail'}
                      onChange={(e, v) => {
                        let arr = []
                        v.map((item, idx) => {
                          console.log('aa',item)
                          arr.push(item.key)
                          // arr.push(item.props.children)
                        })
                        inputChange(arr, 'tags')
                      }}
                      style={{ width: '100%' }}
                    >
                      {tagALL && tagALL.map((item, idx) => {
                        return (
                          <Select.Option key={item.tagId}>{item.name}</Select.Option>
                        )
                      })}
                    </Select>)}
                  </FormItem>
                </Col>
                <Col className="col" span={8}>
                  <FormItem
                    {...formItemLayout}
                    label='作者'>
                    {getFieldDecorator('author', {
                      initialValue: detail.author,
                      rules: [
                        { required: true, whitespace: true, message: '请输入作者' },
                      ],
                    })(<Input
                      placeholder={'请输入作者'}
                      disabled={actionType == 'detail'}
                      onChange={(e) => { inputChange(e.target.value, 'author') }}
                    />)}
                  </FormItem>
                </Col>
              </Row>
              {/* <Row >
              <Col className="col" span={6} hidden={actionType == 'detail'}>
                <FormItem
                  {...formItemLayout}
                  label='编辑方式'>
                  <RadioGroup onChange={(e) => { handleEditType(e) }} value={editValue}>
                    <Radio value={1}>编辑</Radio>
                    <Radio value={2}>外部链接</Radio>
                  </RadioGroup>
                </FormItem>
              </Col>
            </Row> */}
              {/* <Row>
              <Col className="col" span={6} >
                <FormItem
                  {...formItemLayout}
                  label='外部链接'>
                  {getFieldDecorator('link', {
                    initialValue: detail.link || null,
                    rules: [
                      { required: false, whitespace: true, message: '请输入外部链接' },
                    ],
                  })(<Input
                    disabled={disabledLink || actionType == 'detail'}
                    placeholder="请输入外部链接"
                    onChange={(e) => { !disabledLink ? inputChange(e.target.value, 'link') : null }}
                  />)}
                </FormItem>
              </Col>
            </Row> */}
              <Row style={{ display: showEditor }}>
                <Col className="col" span={24} >
                  <FormItem
                    // {...formItemLayout}
                    {...{ labelCol: { span: 2 }, wrapperCol: { span: 22 } }}
                    label='图文编辑'>
                    {(
                      <div>
                        {/* {actionType !== 'detail'&&<span style={{fontSize:12,fontWeight: "normal"}}>注：图文编辑的图片上传尺寸建议：1372px*736px</span>} */}

                        <span style={{ fontSize: 12, fontWeight: "normal" }}>注：图文编辑的图片上传尺寸建议：1372px*736px</span>
                        {/* <span className={'fr'}>
                          <Icon type="question-circle" className={'mgr1'} style={{ color: '#08c' }} />
                          <a href="javascript:void(0)" onClick={() => { changeImgModal(true, [infoDetail_demo]) }}>查看示例</a>
                        </span> */}

                        <Ueditor id="infoDetail"
                          // style={{ width: '100%', height: 900}} 
                          editable={actionType === 'detail' ? false : true}
                          html={detail.detail || ''}
                          // html={detail.detail||'试试直接把编辑好的图文样式复制粘贴到这儿，有惊喜哦~'}
                          title={detail.title || ''}
                          startDate={detail.startDate || ''}
                          endDate={detail.endDate || ''}
                          height={500}
                          enableBtn={isSubmit}
                          // callback={(content) => {handleUeditorContent(content)}}
                          inputChange={e => {
                            dispatch({ type: `${namespace}/dealEditor`, payload: { detail: e } })
                          }}
                          isSubmit={
                            e => { dispatch({ type: `${namespace}/updateStore`, payload: { isSubmit: e.isSubmit } }) }
                          }
                        />



                        {/* <KingEditor
                          id={'infoDetail'}
                          style={{ width: '100%', height: 400 }}
                          editable={actionType === 'detail'?false:true}
                          html={detail.detail||''}
                          inputChange={e => {
                            dispatch({ type: `${namespace}/dealEditor`, payload: { detail: e } })
                          }}
                        /> */}
                      </div>
                    )}
                  </FormItem>
                </Col>
              </Row>
            </CollapsiblePanels>

          </div>
        </Form>
      </div>
      <Modal title={'示例图'}
        onCancel={() => { changeImgModal(false) }}
        onOk={() => { changeImgModal(false) }}
        footer={null}
        width={'80%'}
        visible={imgModal.visible}>
        <Row justify={'space-between'} align={'middle'} type={'flex'}>
          {imgModal.srcs.length == 1 &&
            <Col span={24}>
              <img className={cx('demoImg')} src={imgModal.srcs[0]} alt="" />
            </Col>
          }
          {imgModal.srcs.length == 2 &&
            <Col span={24}>
              <img width={'49%'} src={imgModal.srcs[0]} alt="" />
              <img width={'49%'} className={'fr'} src={imgModal.srcs[1]} alt="" />
            </Col>
          }
        </Row>
      </Modal>
    </div>
  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(routeView))
